import axios from 'axios';
import { Message,Loading} from 'element-ui';  
import router from './../router'
import { appApiKey }  from  './../../static/config'    
/* ajax-get */
export const fetch = (url,data={}) =>{
	return new Promise((resolve,reject) => {
		axios({
			method:'get',
			url:url,
			params:data,
			headers: {
				token:sessionStorage.getItem('username'),
				// app_key:commonUrl.appApiKey  
			}
		}).then(resp=>{ 
			resolve(resp)
		}).catch(err=>{ 
			Loading.service().close();
            if(err.status==500||err.status==404||err.status==400){ 
                Message({
					showClose: true,
					message: '服务器错误！'
				})
            }  
            reject(err);
        })
	})
} 
/* ajax-get */
export const imFetch = (url,data={}) =>{
	return new Promise((resolve,reject) => {
		axios({
			method:'get',
			url:url,
			params:data,
			headers: {
				// token:sessionStorage.getItem('username'),
				'app_key':commonUrl.appApiKey  
			}
		}).then(resp=>{ 
			resolve(resp)
		}).catch(err=>{ 
			Loading.service().close();
            if(err.status==500||err.status==404||err.status==400){ 
                Message({
					showClose: true,
					message: '服务器错误！'
				})
            }  
            reject(err);
        })
	})
} 
/* json-post */
export const postJson = (url,data={}) =>{ 
	return new Promise((resolve,reject)=>{
		axios({
			method:'post',
			url:url,
			data:data,
			headers: {
				token:sessionStorage.getItem('username'),
				// app_key:commonUrl.appApiKey
			}
		}).then(resp=>{ 
			resolve(resp)
		}).catch(err=>{  
			Loading.service().close();
            if(err.status==500||err.status==404||err.status==400){ 
                Message({
					showClose: true,
					message: '服务器错误！'
				})
            } 
            reject(err);
        })
	})
}

/* ajax-post */
export const postData = (url,data={}) =>{
	return new Promise((resolve,reject)=>{
		axios({
			method:'post',
			url:url,
			headers:{
				'Content-type': 'application/x-www-form-urlencoded',
                //  'app_key':commonUrl.appApiKey
			},
			data:data,
			transformRequest: [function (data) {
				let ret = ''
				for (let it in data) {
				  ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
				}
				return ret
			  }],
		}).then(resp=>{ 
			resolve(resp)
		}).catch(err=>{ 
            if(err.status==500||err.status==404){
                Message({
					showClose: true,
					message: '服务器错误！'
				})
            } 
            reject(err);
        })
	})
}
